package cn.tedu.csmall.passport.service.impl;

import cn.tedu.csmall.passport.config.SecurityConfiguration;
import cn.tedu.csmall.passport.ex.ServiceException;
import cn.tedu.csmall.passport.mapper.AdminMapper;
import cn.tedu.csmall.passport.mapper.AdminRoleMapper;
import cn.tedu.csmall.passport.pojo.dto.AdminAddNewDTO;
import cn.tedu.csmall.passport.pojo.dto.AdminLoginDTO;
import cn.tedu.csmall.passport.pojo.entity.Admin;
import cn.tedu.csmall.passport.pojo.entity.AdminRole;
import cn.tedu.csmall.passport.pojo.vo.AdminListItemVO;
import cn.tedu.csmall.passport.pojo.vo.AdminStandardVO;
import cn.tedu.csmall.passport.security.AdminDetails;
import cn.tedu.csmall.passport.service.IAdminService;
import cn.tedu.csmall.passport.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;


@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    AdminRoleMapper adminRoleMapper;
    @Autowired
    public AuthenticationManager authenticationManager;
    @Value("${csmall.jwt.secret-key}")
    private String secretKey;
    @Value("${csmall.jwt.duration-in-minute}")
    private Long durationInMinute;

    @Override
    public String login(AdminLoginDTO adminLoginDTO){
        log.debug("开始处理【管理员登录】的业务，参数：{}", adminLoginDTO);
        //执行认证
        Authentication authentication =
                new UsernamePasswordAuthenticationToken(
                        adminLoginDTO.getUsername(),adminLoginDTO.getPassword()
                );
        Authentication authenticate = authenticationManager.authenticate(authentication);
        log.debug("认证通过,认证管理器返回{}",authenticate);

        //从认证姐多重获取所需要的新信息
        Object principal = authenticate.getPrincipal();
        log.debug("认证结果当事人类型{}",principal.getClass().getName());
        AdminDetails adminDetails = (AdminDetails) principal;
        //用户名
        String username = adminDetails.getUsername();
        //id
        Long id = adminDetails.getId();
        //权限
        Collection<GrantedAuthority> authorities = adminDetails.getAuthorities();
        String authoritiesJsonString = JSON.toJSONString(authorities);

        //生成JWT数据
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",id);
        claims.put("username",username);
        claims.put("authoritiesJsonString",authoritiesJsonString);
        log.debug("向JWT中存入id：{}", id);
        log.debug("向JWT中存入username：{}", username);
        log.debug("向JWT中存入authoritiesJsonString：{}", authoritiesJsonString);
        //生成时间
        Date date = new Date(System.currentTimeMillis()+ durationInMinute * 60 *1000L );
        //固定
        String jwt = Jwts.builder()
                .setHeaderParam("alg","HS256")
                .setHeaderParam("typ","JWT")
                .setClaims(claims)
                .setExpiration(date).signWith(SignatureAlgorithm.HS256,secretKey)
                .compact();
        log.debug("生成Jwt数据{}",jwt);
        return jwt;
    }

    @Override
    public void addNew(AdminAddNewDTO adminAddNewDTO) {
        log.debug("开始处理【添加管理员】的业务，参数：{}", adminAddNewDTO);

        log.debug("即将检查用户名是否被占用……");
        {
            // 从参数对象中获取username
            String username = adminAddNewDTO.getUsername();
            // 调用adminMapper的countByUsername()方法执行统计查询
            int count = adminMapper.countByUsername(username);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加管理员失败，用户名【" + username + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("即将检查手机号码是否被占用……");
        {
            // 从参数对象中获取手机号码
            String phone = adminAddNewDTO.getPhone();
            // 调用adminMapper的countByPhone()方法执行统计查询
            int count = adminMapper.countByPhone(phone);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加管理员失败，手机号码【" + phone + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        log.debug("即将检查电子邮箱是否被占用……");
        {
            // 从参数对象中获取电子邮箱
            String email = adminAddNewDTO.getEmail();
            // 调用adminMapper的countByEmail()方法执行统计查询
            int count = adminMapper.countByEmail(email);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加管理员失败，电子邮箱【" + email + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }

        // 创建Admin对象
        Admin admin = new Admin();
        // 通过BeanUtils.copyProperties()方法将参数对象的各属性值复制到Admin对象中
        BeanUtils.copyProperties(adminAddNewDTO, admin);
        // TODO 取出密码，进行加密处理，并将密文封装回Admin对象中
        // 补全Admin对象中的属性值：loginCount >>> 0
        admin.setLoginCount(0);
        // 调用adminMapper的insert()方法插入数据
        log.debug("即将插入管理员数据，参数：{}", admin);
        int rows = adminMapper.insert(admin);
        // 判断插入数据的结果是否符合预期
        if (rows != 1) {
            String message = "添加管理员失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 插入管理员与角色关联的数据
        Long[] roleIds = adminAddNewDTO.getRoleIds();
        AdminRole[] adminRoles = new AdminRole[roleIds.length];
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < roleIds.length; i++) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(admin.getId());
            adminRole.setRoleId(roleIds[i]);
            adminRole.setGmtCreate(now);
            adminRole.setGmtModified(now);
            adminRoles[i] = adminRole;
        }
        rows = adminRoleMapper.insertBatch(adminRoles);
        if (rows != roleIds.length) {
            String message = "添加管理员失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
    }

    @Override
    public List<AdminListItemVO> list(){
        log.debug("处理查看管理员列表的服务");
        List<AdminListItemVO> list = adminMapper.list();
        //迭代器
        Iterator<AdminListItemVO> iterator = list.iterator();
        //查询 如果有下一个就继续查
        while (iterator.hasNext()){
            //给每个对象赋值
            AdminListItemVO next = iterator.next();
            if (next.getId()==1){
                //删除
                iterator.remove();
                break;
            }
        }
        return list;
    }

    @Override
    public void delete(Long id){
        AdminStandardVO AsVo = adminMapper.getById(id);

        if (id == 1){
            String message = "删除失败,他是一号";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        if (AsVo==null){
            String message = "没有这个数据";
            log.debug(message);
            throw  new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        int i = adminMapper.deleteById(id);
        if (i != 1){
            String message = "删除失败,服务器繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }

        //删除关联数据
        int rows = adminRoleMapper.deleteByAdminId(id);
        if (i < 1){
            String message = "删除失败,服务器繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE,message);
        }
    }

    @Override
    public void setEnable(Long id){
        updateEnableById(id,1);
    }

    @Override
    public void setDisable(Long id){
        updateEnableById(id,0);
    }

    private void updateEnableById(Long id,Integer enable){
        String[] s = {"禁用", "启用"};
        // 判断id是否为1
        if (id ==1) {
            // 是：抛出异常（ERR_NOT_FOUND：s[enable] 管理员失败）
            String message = s[enable]+"管理员失败";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        // 根据id查询管理员详情
        AdminStandardVO ASVO = adminMapper.getById(id);
        // 判断查询结果是否为null
        if (ASVO == null) {
            // 是：抛出异常（ERR_NOT_FOUND）
            String message ="管理员修改失败,没有这个id";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }

        // 判断查询结果中的enable与方法参数enable是否相同
        if (ASVO.getEnable().equals(enable)) {
            // 是：抛出异常（ERR_CONFLICT）
            String message ="管理员修改失败,enable相同";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }
        // 创建Admin对象，并封装id和enable这2个属性的值
        Admin admin = new Admin();
        admin.setId(id);
        admin.setEnable(enable);
        // 调用update()方法执行更新，并获取返回的行数
        int update = adminMapper.update(admin);
        // 判断返回的行数是否不为1
        if (update!=1) {
            // 是：抛出异常（ERR_UPDATE）
            String message ="管理员修改失败,服务器繁忙";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
    }
}
